//
//  MessageListTVC.m
//  ProjectforHDX
//
//  Created by Jaesun on 16/7/1.
//  Copyright © 2016年 H.DX. All rights reserved.
//

#import "MessageListTVC.h"

#import "MessageListCell.h" // 自定义cell

#import "MessageModel.h"



@interface MessageListTVC ()<UITableViewDelegate,UITableViewDataSource> {
    /**
     *  是否可以刷新
     */
    BOOL  isMJRefresh;
    /**
     *  分页
     */
    NSInteger page;
    /**
     *  post 数据
     */
    NSMutableDictionary *postDict;
    /**
     *  修改消息状态时提交数据
     */
    NSMutableDictionary *postMsgDict;
    
    CGFloat rowHeight;
    /**
     *  消息数组
     */
    NSMutableArray <MessageModel *>*messageArr;
}
/**
 *  列表
 */
@property (nonatomic, strong) UITableView *tableView;

@end

@implementation MessageListTVC

static NSString *messageListTableCell_ID = @"messageListCell";

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 下拉刷新数据
    isMJRefresh=YES;
    page=0;
    [self addHeader];
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self setupDatas];

    [self setupViews];
    
 }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

#pragma mark 数据初始化
- (void)setupDatas {
  
    postDict = [NSMutableDictionary dictionary];
    messageArr = [NSMutableArray array];
  
}


#pragma mark 视图初始化
- (void)setupViews {
    
    self.labnav.text = @"消息列表";
    self.labnav.textColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, BOUNDSWIDTH, BOUNDSHEIGHT - 64)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[MessageListCell class] forCellReuseIdentifier:messageListTableCell_ID];
    self.tableView.showsVerticalScrollIndicator = NO;
         self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.view = self.tableView;
    
 
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return messageArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MessageModel *model = [[MessageModel alloc] init];

    model = messageArr[indexPath.row];
    MessageListCell *cell = [[MessageListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:messageListTableCell_ID];
    
    if(cell == nil)
    {
        cell = [[MessageListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:messageListTableCell_ID];
    }
    
    cell.model = model;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageModel *model = [[MessageModel alloc] init];
        model = messageArr[indexPath.row];
    return [self heightForText:model.content] + 55;

}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
    MessageModel *model = [[MessageModel alloc] init];
    model = messageArr[indexPath.row];
    
      

}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UIView *view = [UIView new];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
    
}
#pragma mark- 数据请求
/**
 *  消息列表数据请求
 */
- (void)getMyMessageList {
    
    NSLog(@"page is --%ld",(long)page);

    [[BDHUD sharedManager] dismissHUD];
    
    [postDict setObject:@2 forKey:@"status"];
    [postDict setObject:[NSString stringWithFormat:@"%lu",(long)page] forKey:@"page"];
    {
        [AFHttpTool postJsonDatawithUrl:@"phone1_0!getMyMessageList.action"  parameters:[ postDict mutableCopy] success:^(id responseObject) {
            
            isMJRefresh=YES;
            [self.tableView.header endRefreshing];
            [self.tableView.footer endRefreshing];
            
            if(1==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
                
                if([[responseObject objectForKey:@"data"] isKindOfClass:[NSArray  class]]){
                    
                    NSArray *arr = [responseObject objectForKey:@"data"];
                    if (page == 0) { // 下拉刷新(每次下拉加载时page置0,加载成功后置1)
                        [messageArr removeAllObjects];
                         messageArr = [NSMutableArray arrayWithArray:[UtilCheck arraytoModel:arr targetModel:@"MessageModel"]];
                        
                        if(messageArr.count>0){
                            [self.tableView reloadData];
                            page = 1;
                            [self addFooter];
                        }
                        else {
                            self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
                            [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView top:30  title:[UtilCheck language:@"HUD.noData"] onClick:^{
                                [self.tableView.header beginRefreshing];
                            }];
                            [messageArr removeAllObjects];
                            [self.tableView reloadData];
                        }
                    }
                    else { // 上拉加载
                        arr = nil;
                        if(arr.count>0){
                           [messageArr addObjectsFromArray:[UtilCheck arraytoModel:arr targetModel:@"MessageModel"]];
                            [self.tableView reloadData];
                            page ++;
                        }
                        else {
                           [self.tableView.footer noticeNoMoreData];
                        }
                    }
                }
                else{
                    [[BDHUD sharedManager] showNOneDataViewHUD:self.tableView  top:30 title:[THMangerTool language:@"HUD.noData"]  onClick:^{
                        [self.tableView.header beginRefreshing];
                    }];
                    [messageArr removeAllObjects];
                    [self.tableView reloadData];
                }
            }
            else {
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]&&![UtilCheck DataIsNuLL:[[responseObject objectForKey:@"head"] objectForKey:@"info"]]){
                    [[BDHUD sharedManager] showWords:[[responseObject objectForKey:@"head"] objectForKey:@"info"]];
                }
                [messageArr removeAllObjects];
                [self.tableView reloadData];
            }
        }
        fail:^(id responseObject, NSError *error) {
            
            [self.tableView.header endRefreshing];
            //返回数据出问题 弹出服务器返回信息
            if ([[error.userInfo objectForKey:@"NSLocalizedDescription"] isEqualToString:@"请求超时。"]) {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.time.out"]];
            }else {
                [[BDHUD sharedManager] showWords:[UtilCheck language:@"order.network.interruption"]];
            }
        }];
    }
}


/**
 *  修改消息状态
 */
- (void)setMessageCodeWithMsgID:(NSString *)msgID {
   
    if (!msgID) {
        [[BDHUD sharedManager] showWords:[THMangerTool language:@"setting.message.id.empty"]];
        return;
    }
    postMsgDict = @{@"status":@"1",@"messageId":[NSNumber numberWithInteger:[msgID integerValue]]}.mutableCopy;
    {
        [AFHttpTool postJsonDatawithUrl:@"phone1_0!setMessageCodeById.action"  parameters:[postMsgDict mutableCopy] success:^(id responseObject) {
            
            NSLog(@"responseObject is --%@",responseObject);
            
            if(0==[[[responseObject objectForKey:@"head"] objectForKey:@"status"] intValue]){
                //返回数据出问题 弹出服务器返回信息
                if([[[responseObject objectForKey:@"head"] allKeys] containsObject:@"info"]){
                    NSString *info = [[responseObject objectForKey:@"head"] objectForKey:@"info"];
                    if ([UtilCheck DataIsNuLL:info]) {
                        info = @"状态修改失败";
                    }
                    [[BDHUD sharedManager] showWords:info];
                }

            }
        }
            fail:^(id responseObject, NSError *error) {
                
                                   }];
    }
}

#pragma mark- 其他事件
/**
 *  根据字符就算字符串高度
 *
 *  @param text 字符串
 *
 *  @return 高度
 */
- (CGFloat)heightForText:(NSString *)text {
    
    CGSize size = CGSizeMake(SCREEN_WIDTH - 50, 1000);
    NSDictionary *attributeDic = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
    CGRect rect = [text boundingRectWithSize:size options:(NSStringDrawingUsesLineFragmentOrigin) attributes:attributeDic context:nil];
    CGFloat textHeight = rect.size.height;
    
    return textHeight;
}

/**
 *  返回按钮点击事件
 *
 *  @param sender
 */
- (void)leftItem:(RZCustomButtom *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)addHeader
{
    if(self.tableView.header==nil){
        __weak __typeof(self) weakSelf = self;
        // 添加上拉刷新头部控件
        self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            if(isMJRefresh){
                isMJRefresh=NO;
                page=0;
                // 进入刷新状态后会自动调用这个block
                [weakSelf getMyMessageList];
            }
        }];
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
    }
    else
    {
        // 马上进入刷新状态
        [self.tableView.header beginRefreshing];
        
    }
}

- (void)addFooter
{
    if(self.tableView.footer==nil){
        __weak __typeof(self) weakSelf = self;
        // 添加上拉刷新尾部控件
        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            if(isMJRefresh){
                isMJRefresh=NO;
                // 进入刷新状态后会自动调用这个block
                [weakSelf getMyMessageList];
            }
        }];
        
    }
}



@end
